<template>
	<view class="user-page">
		<view class="top-content" v-if="pageScrollTopFlag" :style="{ height: navBarTop + 'px' }"></view>
		<view
			v-if="isLogin.value && tenant?.option.length"
			class="tenant-popup"
			:style="{
				top: navBarTop + 'px',
				height: navBarHeight + 'px',
				background: pageScrollTopFlag ? 'rgba(255,255,255,0.7)' : ''
			}"
		>
			<wd-drop-menu>
				<wd-drop-menu-item :title="truncatedText" icon="caret-down-small" icon-size="30px" v-model="tenant.value" :options="tenant.option" @change="handleChangeTenant" />
			</wd-drop-menu>
		</view>
		<view
			v-else
			class="tenant-popup"
			:style="{
				top: navBarTop + 'px',
				height: navBarHeight + 'px',
				background: pageScrollTopFlag ? 'rgba(255,255,255,0.7)' : ''
			}"
		>
			家装通
		</view>
		<view class="header" @click="handleView" :style="{ paddingTop: calcAddUp + 'px' }">
			<image :src="userInfo?.avatarUrl"></image>
			<view class="header-con">
				<text v-if="userInfo?.nickName" class="header-con-name">{{ userInfo?.nickName }}</text>
				<view v-if="isLogin.value" class="header-con-location">
					<image class="location-icon" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/location.png"></image>
					{{ userInfo?.residence }}
				</view>
			</view>
			<view v-if="phoneList.length > 0" class="header__phone" @click.stop="handlePhone">
				<image class="header__phone__img" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/contact-phone.png" />
				电话咨询
			</view>
		</view>
		<ViewTabs :isEnable="isEnable" />
		<view v-if="loginErr || (!is500 && !isLogin.value)" class="bg-panel no-login">
			<view class="bg-panel-tip">请先授权，系统会自动匹配为您服务的企业！</view>
		</view>
		<view v-if="is500 && noScanCode" class="bg-panel no-business">
			<view class="bg-panel-tip">未找到商家！请联系商家提供专属小程序码！</view>
		</view>
		<view v-if="(is500 && noPhoneNumber) || (isLogin.value && !userInfo.customerId)" class="bg-panel no-phone">
			<view class="bg-panel-tip">该手机号暂未匹配到相关“合同”请联系企业设计师！</view>
		</view>

		<!-- 登录提示 -->
		<wd-overlay :show="isLogin.popShow" @click="isLogin.popShow = false" :zIndex="99">
			<view class="wrapper">
				<view class="tip">温馨提示</view>
				<view class="info">请先授权登录</view>
				<view class="btn-group">
					<button>取消</button>
					<text class="line" />
					<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="confirm">确认</button>
				</view>
			</view>
		</wd-overlay>
		<template v-if="isLogin.value && userInfo.customerId">
			<!-- start 重要消息 -->
			<important-msg ref="importantMsgComp"></important-msg>
			<!-- end 重要消息 -->

			<!-- start 项目进度 -->
			<circleTitle title="项目进度" more-title="查看验收" @more="viewAcceptance" />
			<Progress v-if="progressList?.length" :data="progressList"></Progress>
			<Empty v-else bgColor="#ffffff" />
			<!-- end 项目进度 -->
			<!-- start 施工日志 -->
			<circleTitle title="施工日志" more-title="查看更多" @more="viewconstruction" />
			<view>
				<ConstructionItem v-for="item in logList" :item="item" :key="item"></ConstructionItem>
				<Empty v-if="!logList?.length" bgColor="#ffffff" />
			</view>
			<!-- end 施工日志 -->
		</template>
		<TabBar :list="tabList" :defaultTab="1" @handelTabBar="handelTabBar" :showPlan="showplan"></TabBar>
		<!-- start phonePopup-->
		<phone-popup v-if="showPhonePopup" v-model:phoneList="phoneList" v-model:showPopup="showPhonePopup"></phone-popup>
		<!-- end phonePopup-->
	</view>
</template>
<script setup>
import { ref, computed, onBeforeMount, onMounted, onUnmounted, watch, nextTick } from 'vue';
import TabBar from '@/components/tabBar/index.vue';
import ViewTabs from './components/viewTab/viewTab.vue';
import { onHide, onPullDownRefresh, onPageScroll } from '@dcloudio/uni-app';
import useTabBarStore from '@/store/modules/base/tabBar';
import useUserStore from '@/store/modules/user/index.js';
import { useTokenStore } from '@/store/modules/token/index.js';
import Progress from './components/progress/index.vue';
import circleTitle from '@/components/circle-title/index.vue';
import ConstructionItem from '@/components/constructionItem/index.vue';
import { getList } from '@/api/construction';
import { getProgressList, getConfig } from '@/api/user.js';
import Empty from '@/components/empty/index.vue';
import { getToken } from '@/api/user';
import PhonePopup from './components/PhonePopup/PhonePopup.vue';
import ImportantMsg from './components/ImportantMsg/ImportantMsg.vue';
import { contactList } from '@/api/user';
import { getTaskList } from '@/api/selfPlan';
const store = useTabBarStore();
const userStore = useUserStore();
const tokenStore = useTokenStore();
const progressList = ref();
const logList = ref([]);
const is500 = ref(false);
const loginErr = ref(false);
const noScanCode = ref(0);
const noPhoneNumber = ref(0);
const showplan = ref(false);
const { tenant, userInfo, isLogin, updateToken, getTenantList, setData } = userStore;
watch(userInfo, (newVal) => {
	nextTick(() => {
		Object.assign(userInfo, newVal);
	});
});

// 导航栏高度
const navBarInfoStorage = uni.getStorageSync('navBarInfoStorage');
const navBarHeight = JSON.parse(navBarInfoStorage)?.navBarHeight || 32;
const navBarTop = JSON.parse(navBarInfoStorage)?.navBarTop || 58;
const calcAddUp = navBarHeight + navBarTop + 20;
const pageScrollTopFlag = ref(false);
onPageScroll((e) => {
	pageScrollTopFlag.value = e.scrollTop > 2;
});

const handleView = () => {
	if (!isLogin.value) {
		isLogin.popShow = true;
	}
};
const getPhoneNumber = async (e) => {
	resetStatus();
	if (e.detail.errMsg === 'getPhoneNumber:ok') {
		// 用户同意授权，获取手机号信息
		const { code } = e?.detail;
		try {
			const { data } = await getToken({
				tenantId: uni.getStorageSync('tenantId'),
				code
			});
			setData(data);
			uni.removeStorageSync('isScan');
			setTimeout(() => {
				getLogProgressList();
				getImportantMsgRequest();
				getContactList();
				getConfigApi(data);
			}, 500);
		} catch (error) {
			console.log('catch>>>>', error);
			is500.value = true;
			if (error?.data?.code === 530) {
				// 未找到商家 联系设计师获取小程序码
				noScanCode.value = 1;
			} else if (error?.data?.code === 535) {
				// 手机号未匹配到合同
				noPhoneNumber.value = 1;
			} else {
				loginErr.value = true;
				// isLogin.popShow = true;
			}
		}
	} else {
		console.error('用户拒绝授权', e.detail.errMsg);
	}
};
const resetStatus = () => {
	is500.value = false;
	loginErr.value = false;
	noScanCode.value = 0;
	noPhoneNumber.value = 0;
};

//电话咨询
const phoneList = ref([]);
const getContactList = async () => {
	const { data } = await contactList();
	phoneList.value = data ?? [];
};
onHide(() => {
	resetStatus();
});
//判断是否显示材料申领图标
const isShowPlan = async () => {
	const { data } = await getTaskList();
	data.forEach((item) => {
		if (item.materialBuyId !== null) {
			showplan.value = true;
		}
	});
};

const isEnable = ref(true);
const getConfigApi = async (cachedUser) => {
	const { data } = await getConfig({ customerId: cachedUser.customerId, tenantId: cachedUser.tenantId });
	uni.setStorageSync('config', data);
	isEnable.value = data?.isEnable;
};
/**
 * 计算导航高度
 */
onBeforeMount(() => {
	tokenStore.syncToken();
	const token = tokenStore.getCookie('token');
	const isScan = uni.getStorageSync('isScan');
	if (token) {
		isShowPlan();
		const cachedUser = uni.getStorageSync('userInfo');
		if (cachedUser) {
			Object.assign(userInfo, cachedUser);
		}
		if (!isScan) {
			// 直接通过最近进入，非扫码，已登录，不调任何接口
			getTenantList();
			getLogProgressList();
			getImportantMsgRequest();
			getContactList();
			getConfigApi(cachedUser);
		}
	}
});
// 处理下拉刷新
onPullDownRefresh(() => {
	getTenantList();
	getLogProgressList();
	getImportantMsgRequest();
	getContactList();
	setTimeout(() => {
		uni.stopPullDownRefresh(); // 停止下拉刷新
	}, 1000);
});

// 获取租户列表
const truncatedText = computed(() => {
	if (tenant?.currentTenant) {
		return tenant.currentTenant.length > 7 ? tenant.currentTenant.substring(0, 7) + '...' : tenant.currentTenant;
	}
});
const getTenantCheckToken = async () => {
	try {
		const res = await updateToken();
		setData(res?.data);
		setTimeout(() => {
			getLogProgressList();
			getImportantMsgRequest();
			getContactList();
			getConfigApi(res?.data);
		}, 500);
	} catch (error) {
		console.log(error);
	}
};

function handleChangeTenant({ value }) {
	try {
		uni.setStorageSync('tenantId', value);
		tenant.value = value;
		tenant.currentTenant = tenant.option.find((item) => item.value === value)?.label || null;
		getTenantCheckToken();
	} catch (error) {
		console.error('切换租户失败', error);
	}
}

// 租户列表 end
const tabList = store.list;
const handelTabBar = (index) => {
	if (!isLogin.value) {
		isLogin.popShow = true;
	} else {
		uni.redirectTo({
			url: tabList[index].pagePath
		});
	}
};
/**
 * 查看验收
 */
const viewAcceptance = () => {
	uni.navigateTo({
		url: '/pages/acceptanceManage/list/list'
	});
};
/**
 * 查看施工日志
 */
const viewconstruction = () => {
	uni.navigateTo({
		url: '/pages/constructionManage/list/list'
	});
};
/**
 * 获取施工日志
 */
const getLogList = async () => {
	try {
		const { data } = await getList({
			size: 3,
			current: 1
		});
		logList.value = data.records || [];
	} catch (error) {
		console.log(error);
	}
};
/**
 * 获取项目进度
 */

const getProgress = async () => {
	const res = await getProgressList();
	progressList.value = res.data || [];
};
/**
 * 获取日志和进度
 */
const getLogProgressList = () => {
	getLogList();
	getProgress();
};

/**
 * 拨打电话
 */
const showPhonePopup = ref(false);
const handlePhone = () => {
	showPhonePopup.value = true;
};

/**
 * 重要消息
 */
const importantMsgComp = ref(null);
const getImportantMsgRequest = () => {
	if (importantMsgComp.value) {
		importantMsgComp.value.getMessageList();
	}
};
</script>
<script>
export default {
	options: {
		styleIsolation: 'shared'
	}
};
</script>
<style lang="scss" scoped>
.user-page {
	padding: 0rpx 25rpx 200rpx 25rpx;
	background: url('http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-bg.png');

	.top-content {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: rgba(255, 255, 255, 0.7);
	}

	.tenant-popup {
		display: flex;
		align-items: center;
		font-size: 36rpx;
		color: #00264a;
		text-align: left;
		margin-bottom: 70rpx;
		position: fixed;
		bottom: 0;
		right: 0;
		left: 0;
		z-index: 99;
		padding-left: 25rpx;

		:deep(.wd-drop-menu) {
			.wd-drop-menu__list {
				display: flex;
				text-align: center;
				background-color: unset;

				.wd-drop-menu__item-title {
					padding: 0 5px;

					&::after {
						opacity: 0;
					}
				}

				.wd-drop-menu__item-title-text {
					margin-right: 45rpx;
					font-size: 36rpx;
					color: #00264a;
					font-weight: bold;
				}

				.wd-icon {
					top: 50% !important;
					transform: translateY(-48%) !important;
					color: #004383;
				}
			}
		}
	}

	.header {
		display: flex;
		position: relative;
		margin-bottom: 40rpx;

		image {
			width: 128rpx;
			height: 128rpx;
			border-radius: 50%;
		}

		&__phone {
			background: #ffffff;
			box-shadow: 0rpx 16rpx 16rpx 0rpx rgba(66, 78, 102, 0.1);
			border-radius: 35rpx 0rpx 0rpx 35rpx;
			border: 2rpx solid #c2d4e8;
			padding: 15rpx 12rpx;
			position: absolute;
			right: -30rpx;
			bottom: 0;
			transform: translateY(-50%);
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #3d3d3d;

			.header__phone__img {
				width: 40rpx;
				height: 40rpx;
				display: inline-block;
				margin-right: 5px;
			}
		}

		&-con {
			padding-left: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			/* align-items: center; */

			&-name {
				font-weight: 400;
				font-size: 32rpx;
				color: #121836;
				line-height: 62rpx;
			}

			&-location {
				font-weight: 400;
				font-size: 24rpx;
				color: #86909c;
				line-height: 62rpx;
				display: flex;
				align-items: center;

				.location-icon {
					width: 28rpx;
					height: 28rpx;
					margin-right: 5px;
				}
			}
		}
	}

	.bg-panel {
		width: 560rpx;
		height: 560rpx;
		margin: 18% auto;
		background-repeat: no-repeat;
		background-size: 100%;
		position: relative;

		&-tip {
			color: red;
			font-weight: 400;
			font-size: 28rpx;
			color: #3d3d3d;
			left: 0;
			right: 0;
			margin: auto;
			text-align: center;
			position: absolute;
			bottom: -15px;
		}
	}

	.no-business {
		background-image: url('http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-search.png');
	}

	.no-login {
		background-image: url('http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-noPermission.png');
	}

	.no-phone {
		background-image: url('http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-messages.png');
	}

	.wrapper {
		width: 622rpx;
		background: #ffffff;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		margin: 80% auto;
		padding-top: 30px;
		box-sizing: border-box;
		text-align: center;
		font-weight: 600;
		font-size: 36rpx;
		color: rgba(0, 0, 0, 0.9);

		.info {
			margin: 20px 0;
			font-weight: 400;
		}

		.btn-group {
			border-top: 1px solid #e7e7e7;
			display: flex;
			justify-content: space-around;
			align-items: center;
			height: 112rpx;

			button {
				width: 50%;
				margin: unset;
				border: unset;
				border-radius: unset;
				font-weight: 500;
				background-color: unset;
				font-weight: 400;
				font-size: 32rpx;
				color: rgba(0, 0, 0, 0.9);
			}

			button::after {
				border: none;
			}

			.confirm {
				color: #007dff;
			}
		}

		.line {
			width: 1rpx;
			height: 100%;
			background: #e7e7e7;
		}
	}
}
</style>
<style>
:deep(.wd-tabbar.is-fixed) {
	bottom: 20px;
}
</style>
